<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use Hash;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
	//后台首页
	Public function getIndex()
	{
		return view('admin.index.index');
	}

	//添加页面
	Public function getAdd()
	{
		return view('admin.user.add');
	}

	//执行添加ffff
	 public  function getInsert(Request $request)
	 {

	 	$this->validate($request, [
        'username' => 'required|max:255',
        'password' => 'required',
        'repassword' => 'required|same:password',
        'email' => 'required|email',
        
    ],[
         'username.required'=>'用户名不能为空',
         'username.max'=>'用户名太长了',
         'password.required'=>'密码不能为空', 
         'repassword.required'=>'确认密码不能为空',
         'repassword.same'=>'两次密码不一致',
         'email.required'=>'邮箱不能为空',
         'email.email'=>'邮箱格式不正确',
         

    ]);

	 	// 上面数据都验证成功
	 	$data = $request->only(['username','password','email']);
	 	$data['token'] = str_random(50);
        $data['password'] = Hash::make($data['password']);
      
           // 执行插入
        $res =  DB::table('user')->insert($data);

        if($res){
            return redirect('/admin/user/list')->with('success','用户添加成功');

        }else{
        	 return back()->with('error','用户添加失败');
        }
	 
	 }

	 // 列表页面
	 public function getList(Request $request){
      
		// echo '用户列表页';
		//查询所有用户数据
		// $users = DB::table('user')->get();
        //$users = DB::table('user')->paginate(2);
        //dd($users);
		//获取分页大小
		$num = $request->input('num',10);
        //var_dump($num);
		//判断是否有关键字
		if($request->input('keywords')){
			$users = DB::table('user')->where('username','like','%'.$request->input('keywords').'%')->paginate($num);
		}else{
			$users = DB::table('user')->paginate($num);
		}
		//获取当前页面接收到的所有参数
		$data = $request->all();
		var_dump($data);

		//解析模板
		return view('Admin.user.list',['users'=>$users]);
	}


	//编辑页面
	 public function getEdit($id){
             	
      $user = DB::table('user')->where('id',$id)->first();
      
      return view('admin.user.edit',['user'=>$user]);
    
     }

    //执行编辑
     public function getUpdate(Request $request){
     
      $id = $request->only(['id']);
      $data= $request -> only(['username','email']);
      $res = DB::table('user')->where('id',$id)->update($data);
      // var_dump($res);
       if($res){
            return redirect('/admin/user/list')->with('success','用户修改成功');

        }else{
        	 return back()->with('error','用户修改失败');
        }
	 
     }

     
     //删除操作
     public  function getDelete($id){
          //dd($request -> input('id'));
     	//dd($id);
     	$res = DB::table('user')->where('id',$id)->delete();
     	if($res){
            return redirect('/admin/user/list')->with('success','用户删除成功');
     	}else{
     		return back()->with('error','用户删除失败');
        }
     	
     }



}

?>